package com.andox.fn.inf.rpc.rest.common;

import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

public class DefaultValueConcurrentHashMap<K, V> extends ConcurrentHashMap<K, V> {
	private static final long serialVersionUID = -6571996325771743271L;
	private Supplier<V> defaultValueSupplier;

	public DefaultValueConcurrentHashMap(Supplier<V> defaultValueSupplier) {
		this.defaultValueSupplier = defaultValueSupplier;
	}

	public V getDefaultValue() {
		return defaultValueSupplier.get();
	}

	@SuppressWarnings("unchecked")
	@Override
	public V get(Object key) {
		V v = super.get(key);
		if (v == null) {
			v = defaultValueSupplier.get();
			this.put((K) key, v);
		}

		return v;
	}
}
